﻿function CDialog(options) {
    var self = this;
    this._dialog = {};
    this._count = 0;
    this._container = "";
    this._options = {
        autoOpen: true,
        buttonFocus: 0,
        buttons: "",
        closeOnEscape: false,
        closeText: 'close',
        closeHide: false,
        frameComplete: null,
        dialogClass: '',
        draggable: true,
        resizable: false,
        hide: 'fade',
        height: 'auto',
        maxHeight: false,
        maxWidth: false,
        minHeight: 150,
        minWidth: 150,
        miniPopup: false,
        modal: true,
        paddingContent: "10px 10px 0",
        paddingTitle: ".3em .2em",
        position: {
            my: 'center',
            at: 'center',
            collision: 'fit',
            using: function (pos) {
                var topOffset = $(this).css(pos).offset().top;
                if (topOffset < 0) {
                    $(this).css('top', pos.top - topOffset);
                }
            }
        },        
        show: 'fade',
        stack: true,
        title: '',
        width: 300,
        zIndex: 1000
    };
    $.extend(true, self._options, options);
    var fn_GetFrame = function (iFrame) {
        var frame = null;
        try {
            if (typeof iFrame == "string") {
                iFrame = $(iFrame);
            }
            if (iFrame && iFrame.length) {
                iFrame = iFrame[0];
                frame = iFrame.contentWindow ? iFrame.contentWindow : iFrame.contentDocument.defaultView;
            }
            return frame;
        }
        catch (ex) {
            return null;
        }
    };
    var fn_ExtendOptions = function () {
        var container = self._container;
        var options = self._options;
        if (self._options.miniPopup) {
            self._options.paddingContent = "2px 2px 0";
            self._options.paddingTitle = "2px";
        }
        if (options.dialogClass) {
            options.dialogClass = "CDialog CDialog-" + options.dialogClass;
        }
        else {
            var dialogClass = "";
            if (typeof container == "string") {
                dialogClass = container.replace(/#|\./g, "");
            }
            else {
                dialogClass = $(container).attr("id") || $(container).attr("class") || "";
                if (dialogClass.indexOf(" ") != -1) {
                    dialogClass = dialogClass.split(" ")[0];
                }
            }
            dialogClass = dialogClass || $.GuidGenerator();
            options.dialogClass = "CDialog CDialog-" + dialogClass;
        }


        var fn_create = options.create;
        options.create = function (event, ui) {
            var $this = $(this);
            $this.parent().appendTo("form");
            /* hide button x-close */
            if (options.closeHide) {
                $this.parent().find("a.ui-dialog-titlebar-close").remove();
            }
            if (options.frameComplete) {
                var fn_FrameLoop = function (count) {
                    var $iFrame = $this.parent().find(".ui-dialog-content").find("iframe");
                    if ($iFrame.length) {
                        try {
                            var iFrame = $iFrame[0];
                            var iFrameWindow = iFrame.contentWindow ? iFrame.contentWindow : iFrame.contentDocument.defaultView;
                            if (iFrameWindow && iFrameWindow.document.readyState == "complete") {
                                options.frameComplete($this, iFrameWindow);
                                return false;
                            }
                            count++;
                            if (count >= 100) {
                                return false;
                            }
                            window.setTimeout(function () {
                                fn_FrameLoop(count);
                            }, 500);
                        }
                        catch (ex) { }
                    }

                };
                if (typeof options.frameComplete == "function") {
                    fn_FrameLoop(0);
                }
            }
            $this.parent().find(".ui-dialog-titlebar").css({ padding: options.paddingTitle });
            $this.css({ padding: options.paddingContent });
            if (!self._options.buttons) {
                $this.addClass("not-ui-dialog-buttonpane");
            }
            if (typeof fn_create == "function") {
                fn_create($this.parent());
            }


        };

        var fn_dragStart = options.dragStart;
        options.dragStart = function (event, ui) {
            var $this = $(this);
            $this.prepend("<div class='CDialog-iFrameFix'></div>");
            if (typeof fn_dragStart == "function") {
                fn_dragStart(event, ui);
            }
        };
        var fn_dragStop = options.dragStop;
        options.dragStop = function (event, ui) {
            var $this = $(this);
            $this.find(".CDialog-iFrameFix").remove();
            if (typeof fn_dragStop == "function") {
                fn_dragStop(event, ui);
            }
        };
    };
    var fn_GuidGenerator = function () {
        var S4 = function () {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        };
        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    };
    this.InitFrame = function (opts) {
        var _options = {
            url: '../../Mods/Blank.html',
            containerID: fn_GuidGenerator(),
            id: fn_GuidGenerator(),
            scrolling: 'no',
            width: '100%',
            height: '100%',
            frameborder: 0
        };
        $.extend(_options, opts);
        var containerID = "CDialog-Container" + _options.id;
        var containerClass = _options.id;
        var frameID = "CDialog-iFrame-" + _options.id;
        var frameborder = _options.frameborder;
        var frameScrolling = _options.scrolling;
        var frameWidth = _options.width;
        var frameHeight = _options.height;
        var frameURL = _options.url;
        var iFrame = ''
        + '<div id="' + containerID + '" class="' + containerClass + '">'
            + '<iframe id="' + frameID + '" allowtransparency="true" frameborder="' + frameborder + '" scrolling="' + frameScrolling + '" width="' + frameWidth + '" height="' + frameHeight + '"  src="' + frameURL + '"></iframe>'
        + '</div>';
        self._options.paddingContent = 0;
        self.Init($(iFrame));
    };
    this.Init = function (container) {
        self._container = container;
        fn_ExtendOptions();
        self._dialog = $(container).dialog(self._options);
        self._count += 1;
    };
    this.Open = function () {
        self._dialog.dialog('open');
    };
    this.Close = function () {
        self._dialog.dialog('close');
    };
    this.isOpen = function () {
        return self._dialog.dialog('isOpen');
    };
    this.Bind = function (type, callback) {
        $(self._container).bind(type, callback);
    };
    this.SetOption = function (type, value) {
        try {
            self._dialog.dialog('option', type, value);
        } catch (e) {
            if (typeof console != "undefined" && typeof console.log != "undefined") {
                console.log("CDialog::SetOption ", e);
            }
        }
    };
    this.SetTitle = function (title) {
        self.SetOption("title", title);
    };
    this.SetWidth = function (width) {
        self.SetOption("width", options.width);
    };
    this.SetHeight = function (height) {
        self.SetOption("height", options.height);
    };
    this.SetSize = function (opts) {
        var options = {
            width: null,
            height: null
        };
        $.extend(options, opts);
        if (options.width) {
            self.SetWidth(options.width);
        }
        if (options.height) {
            self.SetHeight(options.height);
        }
    };
    this.SetButtons = function (arrButtons) {
        self.SetOption("buttons", arrButtons);
    };
}